const net = require('net')
const fs = require('fs')

const fileStream = fs.createWriteStream('./03-socket.txt')

const server = net.createServer()

server.on('connection', (socket) => {
  // 设置socket超时时间
  socket.setTimeout(5 * 1000);

  socket.on('data', (data) => {
    socket.pause()
  })

  socket.on('timeout', () => {
    console.log('超时了--', new Date().toLocaleString())
    socket.resume()

    // 将缓存中的数据写入到文件中
    socket.pipe(fileStream)
  })

  socket.on('end', () => {
    console.log('客户端断开连接')
  })
})

server.listen('8080', () => {
  console.log('服务器启动, 8080端口')
})
